from app.models.AdminPermission import AdminPermission
from app.models.AdminMenu import AdminMenu
from app.models.AdminUser import AdminUser
from app.models.AdminRolePermission import AdminRolePermission
import random
from masonite.facades import Session
from masoniteorm.collection import Collection
from datetime import date, datetime


class MyControllerTrait:
    @classmethod
    def time_format_conversion(cls, data: object) -> object:
        """
        转换时间格式
        """
        if isinstance(data, datetime):
            return data.strftime("%Y-%m-%d %H:%M:%S")
        elif isinstance(data, date):
            return data.strftime("%Y-%m-%d")
        else:
            return data

    @classmethod
    def get_permission_title(cls, uri=''):
        """
        获取访问权限
        @pram string uri: 'admin/menu/index'
        @return: string
        """
        admin_permission = AdminPermission.where('uri', uri.strip('/')).first()
        if admin_permission is None:
            return ""
        return admin_permission.title

    @classmethod
    def get_menu_nav(cls, uri=''):
        """
        获取菜单及其子菜单
        string  uri 'admin/menu/index'
        return list
        """
        uri = uri.strip('/')
        menus = AdminMenu.get_all_pid()
        admin_role_id = Session.get('admin_user')['admin_role_id']
        for index, menu in enumerate(menus):
            # print("id:{0},title:{1}".format(menu['id'], menu['title']))
            child_menus = AdminMenu.where('pid', menu['id']).where('is_show', 1).order_by('rank', 'DESC').get()

            # 是否选中
            menus[index]['focus'] = False
            menus[index]['has_child'] = False
            menus[index]['child_menus'] = []
            for child_menu in child_menus:
                # print(child_menu.id, child_menu.title, child_menu.uri)
                if child_menu.uri == uri:
                    menus[index]['focus'] = True

                if AdminUser.is_super_admin(Session.get('admin_user')['account']):
                    # print({'title': child_menu['title'], 'uri': child_menu['uri']})
                    menus[index]['has_child'] = True
                    menus[index]['child_menus'].append({'title': child_menu['title'], 'uri': child_menu['uri']})
                    continue

                if AdminRolePermission.is_pass(admin_role_id, child_menu['uri']):
                    menus[index]['has_child'] = True
                    menus[index]['child_menus'].append(child_menu)

        # print(menus)
        """
        [
            {
                'id': 1, 
                'title': '系统设置', 
                'focus': True, 
                'child_menus': [
                    {'title': '菜单', 'uri': 'admin/menu/index'}, 
                    {'title': '系统参数', 'uri': 'admin/config/index'}
                ]
            },
        ]
        """
        return menus

    @classmethod
    def export_excel(cls, filename, title, data):
        """
        导出 Excel 文件
        string  filename    文件名
        list    title       标题
        list    data        数据，二维索引数组
        """
        pass

    @classmethod
    def generate_string(cls, length=32, mode='string'):
        """
        生成随机字符串
        @param length:
        @param mode:
        @return: string
        """
        string = "qwertyuiopasdfghjklzxcvbnm1234567890QWERTYUIOPASDFGHJKLZXCVBNM"
        integer = "0123456789"

        str2 = ""
        i = 0
        str1 = string
        if mode == "int":
            str1 = integer

        while i < length:
            str2 += str1[random.randint(0, len(str1) - 1)]
            i += 1
        return str2

    @classmethod
    def keep_decimal_point(cls, num, length=2):
        """
        保留浮点数小数点位数，计算结果是四舍五舍
        float num       浮点数
        int   length    保留结果是四舍五入
        return float
        """
        pass
